import { View, Text, Image, ScrollView } from '@tarojs/components';
import PageContainer from '@/components/PageContainer';
import { DynamicColors, GStyleSheet } from '@/utils/DarkMode';
import { observer } from 'mobx-react';
import { useDeviceDetailStore, useLanguageStore } from '@/hooks';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import { getFAQ } from '@/services/faq';
import { Cell, Collapse, ConfigProvider } from '@taroify/core';
import { Arrow } from '@taroify/icons';
import { useDeviceRect } from '@/hooks/useDeviceRect';
import i18n from 'i18n-js';
import { useStatePlus } from '@/hooks/useStatePlus';
import './index.scss';

export const FromDeviceKey = 'FromDevice';

interface IState {
  list: IFAQ[];
  questionlist: IFAQ[];
  value: number[];
}

const DeviceHelpScreen = () => {
  const [state, setState] = useStatePlus<IState>({ list: [], questionlist: [], value: [] });
  const styles = dstyles.useDynamicStyle();
  const deviceDetailStore = useDeviceDetailStore();
  const { device } = deviceDetailStore;
  const { key } = useLanguageStore();
  const { scrollHeight } = useDeviceRect();
  const {
    params: { type, title },
  } = useRouter();
  const showFooter = type === FromDeviceKey;

  useDidShow(async () => {
    const list = await getFAQ(key, `product_key=${device?.productKey}`);

    if (list.success && list.data) {
      const data = list.data;
      // const data = (list.data as IFAQ[]).filter((i) => {
      //   return i.question !== "";
      // });
      setState({ list: data });
      const promises = data.map(item => {
        return getFAQ(key, `parent_id=${item.id}`);
      });
      Promise.all(promises).then(res => {
        const queList: IFAQ[][] = [];
        res.map((item, index) => {
          if (item.success && item.data) {
            const questions = (item.data as IFAQ[]).filter(i => {
              return i.question !== '';
            });
            queList.push(questions);
          }
        });
        setState({ questionlist: queList.flat() });
      });
    }
  });

  const goFeedback = () => {
    Taro.navigateTo({ url: '/pages/feedback/index' });
  };

  const isNotHelp = state.list.length === 0;

  return (
    <PageContainer title={title || i18n.t('USE_HELP')}>
      <ConfigProvider
        theme={{
          collapseItemContentPadding: '0px',
        }}>
        {isNotHelp ? (
          <View
            className='centerFlex'
            style={{
              height: scrollHeight(30),
            }}>
            <Image
              src='https://xbgroup-1251025085.cos.ap-guangzhou.myqcloud.com/cybertron/users/479438/media/none_1657873343446.png'
              style={{ width: 100, height: 100 }}
            />
          </View>
        ) : (
          <ScrollView className='deviceHelp' scrollY style={{ ...styles.container, height: scrollHeight(30) }}>
            <Collapse value={state.value} onChange={value => setState({ value })}>
              {state.list.length > 1
                ? state.list.map(item => {
                    return (
                      <Collapse.Item title={item.question} key={item.id} extra={<View style={{ width: 0 }}></View>}>
                        {state.questionlist
                          .filter(q => q.parent === item.id)
                          .map(c => {
                            return (
                              <Cell
                                key={c.id}
                                rightIcon={<Arrow />}
                                clickable
                                onClick={() => {
                                  console.log(c);
                                  deviceDetailStore.setFAQDetail(c);
                                  Taro.navigateTo({
                                    url: `/pages/FAQ/index?title=${i18n.t('USE_HELP')}`,
                                  });
                                }}>
                                {c.question}
                              </Cell>
                            );
                          })}
                      </Collapse.Item>
                    );
                  })
                : state.questionlist.map(c => {
                    return (
                      <Cell
                        key={c.id}
                        // title={c.question}
                        rightIcon={<Arrow />}
                        clickable
                        onClick={() => {
                          deviceDetailStore.setFAQDetail(c);
                          Taro.navigateTo({
                            url: `/pages/FAQ/index?title=${i18n.t('USE_HELP')}`,
                          });
                        }}>
                        {c.question}
                      </Cell>
                    );
                  })}
            </Collapse>
          </ScrollView>
        )}
        {showFooter && (
          <View style={styles.footer}>
            <Text style={styles.btnText} onClick={goFeedback}>
              反馈问题
            </Text>
          </View>
        )}
      </ConfigProvider>
    </PageContainer>
  );
};

const dstyles = GStyleSheet.create({
  container: {
    height: '100%',
  },
  footer: {
    height: 30,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  btnText: {
    color: DynamicColors.tintColor,
    fontSize: 14,
  },
});

export default observer(DeviceHelpScreen);
